<?php


namespace App\Http\Controllers;

use App\Services\Tenant\Middleware\InitializeTenancyByUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;


class BaseController extends Controller
{
    public function __construct()
    {
        $this->middleware([
        //'web',
        //'auth',                         //验证登陆中间件会自动初始化使用租户数据库
        //InitializeTenancyByUser::class,   //自定义的中间件也会自动初始化使用租户数据库
    ]);
    }

    public function JyDispatch(Request $request)
    {
        $all = $request->all();
        $mid = $all['mid'] ?? 'index';
        $ctl = $all['ctl'] ?? null;


        if (!$ctl) {
            if (!method_exists($this, $mid)) {
                return response()->json(['message' => "方法 {$mid} 不存在"], 404);
            }
            $rs = App::call([$this, $mid]);
            return $this->baseOut($rs);
        }
        // 构造完整的控制器类名（带命名空间）
        $fullCtlName = __NAMESPACE__ . '\\' . ucfirst($ctl) . 'Controller';

        if (!class_exists($fullCtlName)) {
            return response()->json(['message' => "控制器 {$ctl} 中方法 {$mid} 不存在"], 404);
        }

        // 使用Laravel容器解析控制器实例
        $controller = App::make($fullCtlName);

        if (!method_exists($controller, $mid)) {
            return response()->json(['message' => "控制器 {$ctl} 中方法 {$mid} 不存在"], 404);
        }

        $rs =  App::call([$controller, $mid]);
        return $this->baseOut($rs);

    }

    public function baseOut($data)
    {
        //响应response 不允许bool值,格式化为int
        if (is_bool($data)) {$data = (int)$data;}
        //if (is_int($data)) {$data = json_encode($data);}
        if ('json' ==  request('_view'))
            $rt = response($data);
        else if ('text' ==  request('_view')) {
            $rt = response($data)->content();
        } else {
            $rt = $data;
        }
        return $rt;
    }

    public function apiOut($res, $opt = null){
        $ret  = [
            'data' => $res['data']  ?? null,
            'msg' => $res['msg'] ?? '响应正常',
            'code' => $res['code'] ?? 0
        ];
        if (is_null($ret['data']) &&  !($res['msg'] && $res['code'])) {
            $ret['data'] = $res;
        }
        return response()->json($ret, $opt['http_code'] ?? 200);
    }


}
